package com.bl.mappio.transmit.handler;


import com.bl.common.entity.Message;
import com.bl.common.utils.HttpUtil;
import com.bl.common.utils.StreamUtil;
import com.bl.mappio.proxy.server.ProxyServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

/**
 * @author 作者 : blownsow
 * @version 版本: 1.0
 * @date 创建时间 : 2019/12/7 16:27
 * @describe 类描述:
 */
public class TransmitClientHandler implements Runnable {
    private Socket socket;

    public TransmitClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        InputStream in = null;
        OutputStream out = null;
        try {
            in = socket.getInputStream();
            out = socket.getOutputStream();


            List<byte[]> read = StreamUtil.read(in, true);
            if (read.size() == 0){
                return;
            }
            String content = new String(read.get(0));
            if (content.equals("")){
                return;
            }
            Message message = ProxyServer.proxy(socket.getLocalPort(), content);
            if (message == null || message.getData() == null){
                return;
            }
            Object data = message.getData();
            if (data instanceof String){
                StreamUtil.write(out, HttpUtil.build(data.toString()));
            }else{
                List<byte[]> bytes = (List<byte[]>)data;
                StreamUtil.write(out,bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
